package edge.display.backend.MsgReceiver.Grpc;

import com.alibaba.fastjson.JSONObject;
import edge.display.backend.KEY_STORE;
import edge.display.backend.MsgHandler.QHandler;
import edge.display.backend.Utils.TaskUtils;
import io.grpc.stub.StreamObserver;
import org.lognet.springboot.grpc.GRpcService;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Base64;
import java.util.HashMap;

/**
 * @Description: 从FL读取数据(基于gRPC)并发送至前端
 * @Author: Li Haobo
 * @Date: 2020/10/23
 */

@GRpcService
public class GrpcService extends SendResultGrpc.SendResultImplBase {

    @Override
    public void sendRequest(Datas.toServer request, StreamObserver<Datas.toClient> responseObserver) {
        Datas.toClient client;
        try {
            // io
            String url = String.format(KEY_STORE.DEFAULT_SNAPSHOT_URL, request.getId());
            byte[] bytes = Base64.getDecoder().decode(request.getSnapshot().toStringUtf8());
            OutputStream out = new FileOutputStream(url);
            out.write(bytes);
            out.flush();
            out.close();
            // cut image
            TaskUtils.cutImage(url, "jpg", 1.6f);
            // json
            JSONObject jsonObject = new JSONObject(new HashMap<String, Object>() {
                {
                    put(KEY_STORE.JSON_KEY, KEY_STORE.MSG_TASK_FL);
                    put(KEY_STORE.JSON_VALUE, new HashMap<String, Object>() {
                        {
                            put("id", request.getId());
                            put("t3", request.getArrival());
                            put("snapshot", url);
                            put("result", request.getResult());
                        }
                    });
                }
            });
            QHandler.handle(jsonObject.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        client = Datas.toClient.newBuilder().setReply(1).build();
        responseObserver.onNext(client);
        responseObserver.onCompleted();
    }
}
